生产消费者模式

生产消费者模式

time:26_1_19
多线程开发,生成消费者模式,关键就在与三个参数。互斥。通知 和队列

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <iostream>
#include <thread>
#include <queue>
#include <mutex>
#include <condition_variable>
#include <functional>

// 线程安全队列模板类
template <typename T>
class SafeQueue {
public:
SafeQueue() = default;

// 禁用拷贝构造和赋值操作
SafeQueue(const SafeQueue&) = delete;
SafeQueue& operator=(const SafeQueue&) = delete;

// 入队操作
void enqueue(T item) {
std::lock_guard<std::mutex> lock(m_mutex);
m_queue.push(std::move(item));
m_cond.notify_one();
}

// 出队操作,阻塞等待直到队列非空
T dequeue() {
std::unique_lock<std::mutex> lock(m_mutex);
m_cond.wait(lock, [this]{ return !m_queue.empty(); });
T item = std::move(m_queue.front());
m_queue.pop();
return item;
}

// 尝试出队,不阻塞
bool try_dequeue(T& item) {
std::lock_guard<std::mutex> lock(m_mutex);
if(m_queue.empty()) return false;
item = std::move(m_queue.front());
m_queue.pop();
return true;
}

bool empty() const {
std::lock_guard<std::mutex> lock(m_mutex);
return m_queue.empty();
}

private:
mutable std::mutex m_mutex; // 互斥
std::queue<T> m_queue; // 队列
std::condition_variable m_cond;// 通知
};

// 测试队列和线程
int main() {
SafeQueue<std::function<void()>> tasks;

// 生产者线程
std::thread producer([&tasks]() {
for(int i = 1; i <= 5; i++) {
tasks.enqueue([i]() { std::cout << "Task " << i << " executed"; });
}
});

// 消费者线程
std::thread consumer([&tasks]() {
for(int i = 1; i <= 5; i++) {
auto task = tasks.dequeue();
task();
}
});

producer.join();
consumer.join();

return 0;
}